"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.autoSaveJson = autoSaveJson;
exports.createGraphNodeData = createGraphNodeData;
exports.dbHelper = void 0;
exports.exitFullscreen = exitFullscreen;
exports.getDndConfig = getDndConfig;
exports.getGraphData = getGraphData;
exports.getGraphJSONData = getGraphJSONData;
exports.getLabelText = getLabelText;
exports.getLaneStyle = getLaneStyle;
exports.launchFullScreen = launchFullScreen;
exports.nextTick = nextTick;

var _defaultData = _interopRequireDefault(require("./defaultData"));

var _IndexdbHelper = _interopRequireDefault(require("./components/IndexdbHelper"));

var _excluded = ["moduleType", "name", "x", "y", "systemType", "preId", "id", "image", "bgImage"];

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }

function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }

var dbHelper = new _IndexdbHelper.default('arch_desgin', [{
  name: 'graphDatas',
  keyPath: 'id'
}]); // // 自动保存数据

exports.dbHelper = dbHelper;
var autoSaveTimer;

function autoSaveJson(_x, _x2) {
  return _autoSaveJson.apply(this, arguments);
}

function _autoSaveJson() {
  _autoSaveJson = _asyncToGenerator(function* (graphData, graph) {
    if (autoSaveTimer) clearTimeout(autoSaveTimer);
    return new Promise(resolve => {
      autoSaveTimer = setTimeout( /*#__PURE__*/_asyncToGenerator(function* () {
        yield dbHelper.ready();
        yield new Promise(resolve => setTimeout(resolve, 100));
        var isExist = !!(yield dbHelper.findByPk('graphDatas', '1'));
        var data = {
          id: '1',
          updateTime: Date.now(),
          data: undefined,
          expired: window._saveInterval + 10000
        }; // 如果有 graphData 就强制保存 graphData

        if (graphData) {
          data.data = graphData;
        } else if (graph) {
          // 如果没有 graphData 有graph 就保存 graph 中的数据
          data.data = getGraphJSONData(graph);
        } // 如果都没有 data 为 undefined 将在下次恢复时直接使用 传入的数据


        if (isExist) {
          yield dbHelper.update('graphDatas', data);
        } else {
          yield dbHelper.create('graphDatas', data);
        }

        resolve(1);
      }), 100);
    });
  });
  return _autoSaveJson.apply(this, arguments);
}

function getLaneStyle(index) {
  var nameRectFill = ['#EAFEEC', '#F9F7E6', '#E0EEFA', '#DFE5E6'];
  var nameTextFill = ['#6A8E67', '#978A64', '#495A7F', '#859092'];
  var bottomBorderStroke = ['#9BD787', '#E1BD81', '#7BA3FC', '#859092'];
  return {
    nameRect: {
      fill: nameRectFill[index]
    },
    nameText: {
      fill: nameTextFill[index]
    },
    bottomBorder: {
      stroke: bottomBorderStroke[index]
    }
  };
}

function getGraphData(dataSource) {
  if (!dataSource) return _defaultData.default;
  var {
    lanes = [],
    nodes = [],
    links = []
  } = dataSource;
  var lh = 25;
  var maxWidth = 0;
  var laneList = lanes.map((data, i) => {
    var {
      id,
      height,
      x,
      y,
      name,
      width
    } = data;
    lh += height;
    data.type = 'lane';
    data.sort = i;
    maxWidth = Math.max(maxWidth, width || 0);
    var laneData = {
      id,
      shape: 'lane',
      data,
      height,
      label: (name || '').split('').join('\n'),
      position: {
        x: x || 0,
        y: y || lh - height
      },
      attrs: getLaneStyle(i % 4)
    };
    return laneData;
  });
  var nodeList = nodes.map(createGraphNodeData);
  maxWidth = Math.max(maxWidth, ...nodeList.map(node => (node.position.x || 0) + 200));
  var linkList = links.map(link => {
    var {
      id,
      source,
      target
    } = link;
    link.type = 'link';
    return {
      id: id || "".concat(source, "_").concat(target),
      shape: 'lane-edge',
      source,
      target,
      data: link
    };
  });
  return {
    width: maxWidth,
    height: lh + 25,
    laneList,
    nodeList,
    linkList
  };
} // 两行显示名称

/**
 * 用于实例详情图中任务名称显示
 * @param {string} label 需要处理的字符
 * @param {number} maxTextLen 最大长度 默认20
 * @param {number} maxLine  最大行数 默认1
 * @param {string} placehoder 中间占位字符 默认...
 */


function getLabelText(_ref) {
  var {
    label = '',
    placehoder = '...',
    maxTextLen = 20,
    maxLine = 2
  } = _ref;
  var textList = [];
  var len = 0;
  var lineCount = 0;
  (label || '').split('').every(char => {
    var crrLen;
    if (len === 0) textList[textList.length] = [];
    if (/[ilI]/.test(char)) crrLen = 0.5;else if (/[A-Z]/.test(char)) crrLen = 1.5;else if (/[^\u0000-\u00FF]/.test(char)) crrLen = 2;else crrLen = 1;

    if (lineCount === maxLine - 1 && crrLen + len >= maxTextLen - placehoder.length) {
      textList[textList.length - 1].push(placehoder);
      return false;
    }

    if (crrLen + len < maxTextLen + 1) {
      textList[textList.length - 1].push(char);
      len += crrLen;
    } else if (lineCount < maxLine) {
      textList[textList.length] = [char];
      len = crrLen;
      lineCount += 1;
    }

    return true;
  });
  return textList.map(list => list.join('')).join('\n');
}

function nextTick(callback) {
  return Promise.resolve().then(callback);
}

function getDndConfig(target) {
  return {
    target,
    // delegateGraphOptions
    validateNode: () => false,
    animation: true,
    getDragNode: () => {},
    getDropNode: () => {}
  };
} // 将配置数据转换成节点所需数据


function createGraphNodeData(nodeData, config) {
  var {
    graph,
    assets
  } = config || {};

  var {
    moduleType,
    name,
    x,
    y,
    systemType,
    preId,
    id: nodeId,
    image,
    bgImage
  } = nodeData,
      rest = _objectWithoutProperties(nodeData, _excluded);

  var id = nodeId;

  if (!id) {
    id = "".concat(Date.now().toString(32), "_").concat(Math.floor(Math.random() * 100000).toString(32));
  }

  var data = {
    type: 'node',
    image: image || "".concat((moduleType || '').toLowerCase(), "Module"),
    bgImage: bgImage || "".concat((systemType || '').toLowerCase(), "System")
  };
  var position = {
    x: 0,
    y: 0
  };
  var attrs = {};

  if (x !== undefined && y !== undefined) {
    position = {
      x,
      y
    };
  } else if (graph && preId) {
    var lane = graph.getCellById(preId);
    var {
      x: _x3,
      y: _y
    } = lane.position();
    position = {
      x: _x3 + 60,
      y: _y + 10
    };
  }

  if (assets) {
    attrs = {
      itemTag: {
        xlinkHref: assets[data.image]
      },
      backgorund: {
        xlinkHref: assets[data.bgImage]
      }
    };
  }

  return {
    id,
    shape: 'lane-node',
    position,
    parent: preId,
    data: _objectSpread(_objectSpread({
      moduleType,
      name,
      systemType,
      preId,
      id
    }, rest), data),
    attrs,
    label: getLabelText({
      label: name,
      maxTextLen: 20,
      maxLine: 2,
      placehoder: '...'
    })
  };
} // 将画布中的所有元素转换成 后端保存数据


function getGraphJSONData(graph) {
  var {
    cells
  } = graph.toJSON();
  var {
    clientWidth,
    clientHeight
  } = graph.container;
  var lanes = [];
  var nodes = [];
  var links = [];
  cells.forEach(cell => {
    var {
      shape,
      position,
      size,
      data,
      parent,
      zIndex,
      source,
      target
    } = cell;

    if (shape === 'lane-edge') {
      links.push({
        source: source.cell,
        target: target.cell,
        zIndex: zIndex || 2
      });
    } else {
      var node = _objectSpread(_objectSpread(_objectSpread(_objectSpread({}, data), size), position), {}, {
        preId: parent
      });

      if (shape === 'lane') {
        node.zIndex = zIndex || 1;
        lanes.push(node);
      } else {
        node.zIndex = zIndex || 2;
        nodes.push(node);
      }
    }
  }); // console.log(266, lanes, nodes);

  return {
    width: clientWidth,
    height: clientHeight,
    lanes,
    nodes,
    links
  };
}

function launchFullScreen(element) {
  if (element.requestFullscreen) {
    element.requestFullscreen();
  } else if (element.mozRequestFullScreen) {
    element.mozRequestFullScreen();
  } else if (element.webkitRequestFullscreen) {
    element.webkitRequestFullscreen();
  } else if (element.msRequestFullscreen) {
    element.msRequestFullscreen();
  }
}

function exitFullscreen() {
  if (document.exitFullscreen) {
    document.exitFullscreen();
  } else if (document.mozCancelFullScreen) {
    document.mozCancelFullScreen();
  } else if (document.webkitExitFullscreen) {
    document.webkitExitFullscreen();
  }
}